package ca.llsutherland.squash.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import ca.llsutherland.squash.domain.Clock;
import ca.llsutherland.squash.domain.CourtStyle;
import ca.llsutherland.squash.domain.helper.CourtStylesHelper;
import ca.llsutherland.squash.exceptions.ValidationException;
import ca.llsutherland.squash.utils.StringUtils;

public class CourtStylesDao extends BaseDao {

    private static CourtStylesDao instance = new CourtStylesDao();

    @Override
    public String getUnderlyingTableName() {
        return "COURT_STYLES";
    }

    public static CourtStylesDao getInstance() {
        return instance ;
    }

    public CourtStyle findByName(String name) {
        String findByNameQuery = getFindByNameQuery(name);
        return buildCourtStyle(findByNameQuery);
    }

    private CourtStyle buildCourtStyle(String sql) {
        CourtStyle courtStyle = null;
        ResultSet rs = super.findByQuery(sql);
        
        try {
            if(rs.next()){
                String name = rs.getString("NAME");
                Clock dateCreated = new Clock(rs.getTimestamp("DATE_CREATED").getTime());
                Clock dateUpdated = new Clock(rs.getTimestamp("DATE_UPDATED").getTime());
                Long id = Long.valueOf(rs.getLong("ID"));
                
                courtStyle = CourtStylesHelper.createNewCourtStyle(name, dateCreated, dateUpdated, id);
            }
            rs.close();
        } catch (SQLException e) {
            throw new ValidationException(e.getMessage() + " in buildCourtStyle()");
        } finally {
            rs = null;            
        }
        return courtStyle;
    }

    public CourtStyle create(CourtStyle courtStyle) {
        String sql = "INSERT INTO " + getUnderlyingTableName() + "(ID, NAME, DATE_CREATED, DATE_UPDATED) VALUES (" 
            + courtStyle.getId() + ", "
            + StringUtils.addSingleQuotes(courtStyle.getName()) + ", "
            + StringUtils.addSingleQuotes(courtStyle.getDateCreated().toString()) + ", "
            + StringUtils.addSingleQuotes(courtStyle.getDateUpdated().toString()) + ");";
        return findById(super.create(sql));
    }

    public CourtStyle findById(Long id) {
        String findByIdQuery = getFindByIdQuery(id);
        return buildCourtStyle(findByIdQuery);
    }

}
